package com.by.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        HttpHeaders headers = exchange.getRequest().getHeaders();
        //获取令牌
        String token = headers.getFirst("token");
        if (null == token) {
            //没有权限
            ServerHttpResponse response = exchange.getResponse();
            //设置响应内容类型
            // response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
            response.getHeaders().set("Content-Type", "text/plain;charset=utf-8");
            DataBuffer buffer = response.bufferFactory().wrap("没有token,无取访问".getBytes());
            return response.writeWith(Mono.just(buffer));
        }
        //有权限 放行 进入下一环节(过滤器 或 微服务 )
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}